package cn.aitrox.ry.util;


import cn.aitrox.ry.bean.CommonPageInfo;

import java.util.ArrayList;
import java.util.List;

public class LogicPageUtil {
    public static final Integer DEFAULT_PAGE = 1;
    public static final Integer DEFAULT_PAGESIZE = 10;
    public static final Integer MIN_PAGESIZE = 1;
    public static final Integer ALL_PAGESIZE = -1;

    public static <T> CommonPageInfo<T> pagination(Integer page, Integer pageSize, List<T> data) {
        if (ArrayUtil.isEmpty(data)) {
            return new CommonPageInfo<T>(0, 0, new ArrayList<>());
        }
        if (null != pageSize && pageSize.equals(ALL_PAGESIZE)) { // 查询所有
            return new CommonPageInfo<T>(0, 0, data);
        }
        page = (null == page || page < DEFAULT_PAGE) ? DEFAULT_PAGE : page;
        pageSize = (null == pageSize || pageSize < MIN_PAGESIZE) ? DEFAULT_PAGESIZE : pageSize;
        int start = (page - 1) * pageSize;
        int end = start + pageSize;
        int total = data.size();
        int pages = (total % pageSize == 0) ? (total / pageSize) : (total / pageSize + 1);
        List list = null;
        if (total > start) {
            if (total > end) {
                list = data.subList(start, end);
            } else {
                list = data.subList(start, total);
            }
        }
        return new CommonPageInfo<T>(total, pages, list);
    }

}
